package com.ruoyi.web.controller.system;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.IMaterialService;
import com.ruoyi.system.service.IProjectsService;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 材料Controller
 *
 * @author ruoyi
 * @date 2020-12-16
 */
@RestController
@RequestMapping("/system/material")
@Transactional
public class MaterialController extends BaseController {

    @Autowired
    private IMaterialService materialService;
    @Autowired
    private IProjectsService projectsService;

    /**
     * 查询材料列表   要知道明细记录在那个表中
     */
    @PostMapping("/detail/list")
    public TableDataInfo list(Material material, Integer pid) {
        startPage();
        List<MaterialEight> list = materialService.selectMaterialList(material, pid);
        return getDataTable(list);
    }

    @PostMapping("//list")
    public TableDataInfo matelist(Long pId) {
        startPage();
        List<HashMap> hashMaps = materialService.projectCost(pId);
        return getDataTable(hashMaps);
    }

    @GetMapping("/cost/list")
    public TableDataInfo list(Long pId) {
        startPage();
        List<HashMap> hashMaps = materialService.projectCost(pId);
        return getDataTable(hashMaps);
    }

    @Log(title = "材料", businessType = BusinessType.EXPORT)
    @PostMapping("/detail/export")
    public AjaxResult exportlist(Material material, Integer pid) {
        List<MaterialEight> list = materialService.selectMaterialList(material, pid);
        ExcelUtil<MaterialEight> util = new ExcelUtil<MaterialEight>(MaterialEight.class);
        return util.exportExcel(list, "material");
    }

    /**
     * 新增保存材料
     */
    @Log(title = "项目材料", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult addSave(@RequestBody MaterialThree materialThree) {
        if (materialService.insertMaterialproject(materialThree) > 0) {

            return AjaxResult.success();
        } else {
            return AjaxResult.error("材料已存在");
        }
    }

    /**
     * 删除
     */
    @Log(title = "项目材料", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    public AjaxResult remove(long pid, long ids) {
        if (materialService.deleteMaterial(pid, ids) > 0) {
            return success();
        } else {
            return error("材料使用中");
        }
    }

    /**
     * 查询材料列表
     */
    @PostMapping("/listAll")
    public TableDataInfo listQuery(Material material, Integer pid) {
        startPage();
        List<Material> list = materialService.selectMaterialListQuery(material, pid);
        return getDataTable(list);
    }

    /**
     * 查询总领料总退料
     */
    @PostMapping("/count")
    public TableDataInfo count(Long mid, Integer pid) {
        List<Long> count = materialService.selectCount(mid, pid);
        return getDataTable(count);
    }

    /**
     * 导出材料列表
     */
//    @RequiresPermissions("system:material:export")
    @Log(title = "材料", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public AjaxResult export(Material material, Integer pid) {
        List<Material> list = materialService.selectMaterialListQuery(material, pid);
        ExcelUtil<Material> util = new ExcelUtil<Material>(Material.class);
        return util.exportExcel(list, "material");
    }


    @PostMapping("/intomaterial")
    public TableDataInfo searchByMid(PickCondition pickCondition, Long mId) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("pickCondition", pickCondition);
        map.put("mId", mId);
        List<PickCondition> pickConditions = materialService.searchByMid(map);
        return getDataTable(pickConditions);
    }

    /**
     * 领料
     */
    @PostMapping("/picking")
    public AjaxResult picking(@RequestBody List<PickCondition> list) {
        boolean reslut = true;
        for (int i = 0; i < list.size(); i++) {
            PickCondition pickCondition = list.get(i);
            boolean pick = materialService.pick(pickCondition);
            reslut = reslut && pick;
        }
        if (reslut) {
            return success("领料成功");
        } else {
            return error("领料失败");
        }


    }


    /**
     * 退料弹窗回显
     */
    @PostMapping("/returning")
    public TableDataInfo returning(Material material, Long mId, Long pId) {
        HashMap<String, Object> map = new HashMap();
        map.put("material", material);
        map.put("mId", mId);
        map.put("pId", pId);
        List<PickCondition> pickConditionList = materialService.selectMatById(map);
        return getDataTable(pickConditionList);
    }

    /**
     * 退料仓库列表
     */
    @GetMapping("/returnWares")
    public TableDataInfo returnWares() {
        List<String> wares = materialService.sreturnWares();
        return getDataTable(wares);
    }

    /**
     * 退料仓库列表
     */
    @GetMapping("/materials")
    public TableDataInfo materials(Material material) {
        startPage();
        List<Material> wares = materialService.queryMaterials(material);
        return getDataTable(wares);
    }

    /**
     * 退料
     */
    @PostMapping("/returnWare")
    public AjaxResult returnWare(@RequestBody List<PickCondition> list) {
        boolean reslut = true;
        for (int i = 0; i < list.size(); i++) {
            PickCondition pickCondition = list.get(i);
            boolean returnWare = materialService.returnWare(pickCondition);
            reslut = reslut && returnWare;
        }
        if (reslut) {
            return success("退料成功");
        } else {
            return error("退料失败");
        }
    }

    @PostMapping("/uplod")
    @CrossOrigin
    public void uplod(Long pId, HttpServletResponse response) {
        try {
            List<HashMap> hashMaps = materialService.projectCost(pId);
            Projects projects = projectsService.selectProjectsById(pId);
            List<Object> list = new ArrayList<>();
            // 表一数据
            Double sum=0.0;
            for (int i = 0; i < hashMaps.size(); i++) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", i + 1);
                map.put("m_name", hashMaps.get(i).get("m_name"));
                map.put("m_model", hashMaps.get(i).get("m_model"));
                map.put("unit", hashMaps.get(i).get("unit"));
                map.put("md_specifications", hashMaps.get(i).get("md_specifications"));
                map.put("md_price", hashMaps.get(i).get("md_price"));
                if ((Integer) hashMaps.get(i).get("md_type") == 0) map.put("md_type", "甲供");
                if ((Integer) hashMaps.get(i).get("md_type") == 1) map.put("md_type", "乙供");
                map.put("money", hashMaps.get(i).get("money"));
                map.put("lingliao", hashMaps.get(i).get("lingliao"));
                map.put("tuiliao", hashMaps.get(i).get("tuiliao"));
                map.put("sj", hashMaps.get(i).get("sj"));
                sum+=Double.valueOf(hashMaps.get(i).get("money").toString());
                list.add(map);
            }
            // 表格使用的数据
            Map map = new HashMap();
            map.put("proName", projects.getpName());
            map.put("proNumber", projects.getpNumber());
            map.put("sum", sum);
            map.put("data", list);//放入表一数据
            // 获取模板文件
            //读取模板
            TemplateExportParams params = new TemplateExportParams("/home/ruoyi/excel/项目成本.xlsx");
            Workbook workbook = ExcelExportUtil.exportExcel(params, map);
//            FileOutputStream out = new FileOutputStream("C:\\Users\\Win10\\Desktop\\项目成本1.xlsx");
            workbook.write(response.getOutputStream());
//            workbook.write(out);
            workbook.close();
//            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
